package com.spboot.exts.controller;

import java.io.File;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.apache.velocity.shaded.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spboot.exts.entity.User;
import com.spboot.exts.entity.ajax.AjaxJsonResult;
import com.spboot.exts.entity.util.PageInfo;
import com.spboot.exts.exception.AjaxAuthorizationException;
import com.spboot.exts.service.RoleService;
import com.spboot.exts.service.UserService;
import com.spboot.exts.utlis.ClassUtils;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author test
 * @since 2019-08-31
 */
@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	UserService userService;
	
	@Autowired
	RoleService roleService;
	
	@GetMapping("/logout")
	public String logout(){
		SecurityUtils.getSubject().logout();
		return "/";
	}

	@RequestMapping("/login")
	public String login(String userCode, String userPassword, Model model, HttpSession session) {
		UsernamePasswordToken token = new UsernamePasswordToken(userCode, userPassword);
        //当前用户
		Subject subject = SecurityUtils.getSubject();
        try {
        	//用户登录验证
            subject.login(token);
        } catch (IncorrectCredentialsException ice) {
        	model.addAttribute("msg", "密码错误");
            return "login";
        } catch (UnknownAccountException uae) {
        	model.addAttribute("msg", uae.getMessage());
            return "login";
        }
        //登录成功
		User user = userService.getOne(new QueryWrapper<User>().eq(User.USERCODE, userCode));

		subject.getSession().setAttribute("userSession", user);
		return "redirect:/index";
	}

	
	//使用注解必须开启AOP切面
	@RequiresPermissions("user_list")
	@GetMapping("/list")
	public String list(String userName, 
			Integer userRole,
			@RequestParam(defaultValue = "1",required = false) Integer pageno,
			Model model) {
		//连接查询中 获取表名 
		String userTableName = ClassUtils.getTableName(User.class);
		
		QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
		
		if(!StringUtils.isEmpty(userName)){
			queryWrapper.likeRight(userTableName + "."+User.USERNAME, userName);
		}
		if(userRole != null && userRole != 0){
			queryWrapper.eq(userTableName + "."+User.USERROLE, userRole);
		}
		//默认查询未删除
		queryWrapper.eq(userTableName+".isDelete", 0);
		PageInfo<User> pageInfo  =new PageInfo<User>(pageno, 8);
		pageInfo = (PageInfo<User>) userService.selectUserPage(pageInfo, queryWrapper);
//		List<User> userList = userService.list(queryWrapper);

		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("roleList", roleService.list());
		model.addAttribute("userName", userName);
		model.addAttribute("userRole", userRole);
		return "user_list";
	}

	@RequiresPermissions("user_del")
	@GetMapping("/del") //get
//	@RequestMapping("/") //get post
//	@PostMapping//post
	public String del(Long id,Integer pageno){
//		User user = userService.getById(id);
//		user.setIsDelete(1);//标识删除
		boolean f = userService.removeById(id);
//		userService.updateById(user);
		return "redirect:list?pageno="+pageno;
	}

	/**
	 * 
	 * @param id
	 * @return
	 * @throws AjaxAuthorizationException ajax操作时未授权
	 */
	@ResponseBody
	@RequiresPermissions("user_get")
	@GetMapping("/get/{id}")
	public AjaxJsonResult get(@PathVariable Long id) throws AjaxAuthorizationException{
		User user = userService.getById(id);
		return AjaxJsonResult.success("操作成功!",user);
	}

	@RequiresPermissions("user_toadd")
	@GetMapping("/toadd")
	public String toAdd(Model model){
		//加载角色
		model.addAttribute("roleList", roleService.list());
		return "user_add";
	}

	@RequiresPermissions("user_add")
	@PostMapping("/add")
	public String add(User user,MultipartFile idPicFile,Model model){
		//文件上传
		try {
			if(!idPicFile.isEmpty()){
				String fileName = 
						System.currentTimeMillis() + "." + 
						FilenameUtils.getExtension(idPicFile.getOriginalFilename());
				idPicFile.transferTo(new File("E:\\static\\" + fileName));
				
				user.setIdPicPath(fileName);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		boolean f = userService.save(user);
		if(f){
			return "redirect:list";
		}
		model.addAttribute("msg", "添加失败");
		model.addAttribute("roleList", roleService.list());
		return "user_add";
	}

}
